package channelService

import (
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelLogger"
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelStatus"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Hex"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Reflect"
	"go-fox-edge-channel-mqtt-client/channelEvent"
)

type reportService struct {
}

func (e *reportService) popAll(channelType string) ([]*commRedisRpc.ChannelRespondVO, error) {
	respondVOList := make([]*commRedisRpc.ChannelRespondVO, 0)

	for channelEvent.List.HasMessage() {
		data := channelEvent.List.Wait(1000)

		// 取出deviceKey
		deviceKey := Map.GetString(data, "deviceKey", "")
		if deviceKey == "" {
			continue
		}

		// 取出channelName
		channelName, _ := service.deviceKeyMap.Load(deviceKey)
		if channelName == nil {
			continue
		}

		payload := data["payload"]
		if payload != nil && Reflect.IsBytes(payload) {
			payload = Hex.EncodeToString(payload.([]byte))
		}

		respondVO := commRedisRpc.Type.ChannelRespondVO.New()
		respondVO.Type = channelType
		respondVO.Name = channelName.(string)
		respondVO.Recv = payload

		respondVOList = append(respondVOList, respondVO)

		// 更新接收状态
		channelStatus.Traffic.ActiveTrafficUploadPack(channelName.(string))

		channelLogger.PrintChannelDebugLogger(respondVO.Name, "上报", respondVO.Recv)
	}

	return respondVOList, nil
}
